import React, { useEffect, useState, useRef } from 'react'
import { Table, Button, Space, Modal, Switch, Form } from 'antd'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import UserList from './UserList'
import axios from 'axios'

const { confirm } = Modal
export default function List() {
  const [form] = Form.useForm()
  const [dataSource, setDataSource] = useState([])
  const [isAddVisible, setIsAddVisible] = useState(false)

  const [roleList, setRoleList] = useState([])
  const [regionList, setRegionList] = useState([])

  const [isAddStatus, setIsAddStatus] = useState(false)
  const [isUpdateDisable, setIsUpdateDisable] = useState(false)
  const [currenItem, setCurrenItem] = useState(null)

  const addFormRef = useRef(null)
  const { roleId, region, username } = JSON.parse(
    localStorage.getItem('xinwen-token')
  )
  useEffect(() => {
    getTableList()
    getRoleList()
    getRegionList()
  }, [])
  const getTableList = () => {
    axios.get('/users?_expand=role').then((res) => {
      let list = res.data

      // 普通用户只能拿到本区域的数据
      if (roleId === 1) {
        setDataSource(list)
      } else {
        let newList = list.filter((item) => {
          return (
            item.username == username ||
            (item.region === region && item.roleId === 3)
          )
        })
        setDataSource(newList)
      }
    })
  }
  const getRoleList = () => {
    axios.get('/roles').then((res) => {
      let a = res.data
      let list = a.map((item) => {
        item.label = item.roleName
        item.value = item.roleType
        return item
      })
      setRoleList(list)
    })
  }
  const getRegionList = () => {
    axios.get('/regions').then((res) => {
      setRegionList(res.data)
    })
  }

  const comfirmHandler = (item) => {
    confirm({
      title: '确定要删除吗?',
      icon: <ExclamationCircleOutlined />,
      content: 'Some descriptions',
      onOk() {
        deleteHandler(item)
      },
      onCancel() {},
    })
  }
  const deleteHandler = (item) => {
    axios.delete('/users/' + item.id).then((res) => {
      getTableList()
    })
  }

  const switchHandle = (item, checked) => {
    axios
      .patch('/users/' + item.id, {
        roleState: checked,
      })
      .then((res) => {
        getTableList()
      })
  }

  const hangdlerUpdate = (item) => {
    setCurrenItem(item)
    setIsAddStatus(false)
    setIsAddVisible(true)
    // 判断子组件是否禁用部分状态
    item.roleId === 1 ? setIsUpdateDisable(true) : setIsUpdateDisable(false)
    setTimeout(() => {
      addFormRef.current.setFieldsValue(item)
    }, 0)
  }

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters: [
        ...regionList.map((item) => {
          return {
            text: item.title,
            value: item.value,
          }
        }),
        {
          text: '全球',
          value: '全球',
        },
      ],
      onFilter: (value, item) => {
        if (value === '全球') {
          return item.region === ''
        } else {
          return item.region === value
        }
      },
      render: (region) => {
        return region ? region : '全球'
      },
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        return role.roleName
      },
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return (
          <Switch
            checked={roleState}
            disabled={item.default}
            onChange={(checked) => {
              switchHandle(item, checked)
            }}
          ></Switch>
        )
      },
    },
    {
      title: '操作',
      render: (item) => {
        return (
          <div>
            <Space>
              <Button
                danger
                type="primary"
                shape="circle"
                icon={<DeleteOutlined />}
                onClick={() => comfirmHandler(item)}
              ></Button>

              <Button
                type="primary"
                shape="circle"
                icon={<EditOutlined />}
                onClick={() => hangdlerUpdate(item)}
              ></Button>
            </Space>
          </div>
        )
      },
    },
  ]

  const adduser = () => {
    setIsAddStatus(true)
    setIsUpdateDisable(false)
    setIsAddVisible(true)
  }
  const onCreate = (values) => {
    console.log('Received values of form: ', values)
  }

  const addFormOk = () => {
    {
      addFormRef.current
        .validateFields()
        .then((values) => {
          if (isAddStatus) {
            axios
              .post('/users', {
                ...values,
                roleState: true,
                default: false,
              })
              .then((res) => {
                addFormRef.current.resetFields()
                setIsAddVisible(false)
                getTableList()
              })
          } else {
            axios
              .patch('/users/' + currenItem.id, {
                ...currenItem,
                ...values,
              })
              .then((res) => {
                addFormRef.current.resetFields()
                setIsAddVisible(false)
                getTableList()
              })
          }
        })
        .catch((info) => {
          console.log('Validate Failed:', info)
        })
    }
  }
  return (
    <>
      <Button type="primary" onClick={adduser}>
        添加用户
      </Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5,
        }}
        rowKey={(item) => item.id}
      />
      {isAddVisible ? (
        <Modal
          open={isAddVisible}
          title={isAddStatus ? '添加用户' : '编辑'}
          okText="确定"
          cancelText="取消"
          onCancel={() => {
            setIsAddVisible(false)
            setIsUpdateDisable(false)
            addFormRef.current.resetFields()
          }}
          onOk={() => addFormOk()}
        >
          <UserList
            regionList={regionList}
            roleList={roleList}
            ref={addFormRef}
            isUpdateDisable={isUpdateDisable}
          />
        </Modal>
      ) : null}
    </>
  )
}
